/* 
  1.该文件是用于创建一个为Count组件服务的reducer，reducer的本质就是一个函数
  2.reducer函数会接到两个参数，分别为：之前的状态(preState)，动作对象(action)
*/

const initState = 0 //初始化状态
export default function countReducer(preState = initState, action) {
  // console.log(preState);
  //从action对象中获取：type、data
  const { type, data } = action
  //根据type决定如何加工数据
  switch (type) {
    case 'increment': //如果是加
      return preState + data
    case 'decrement': //若果是减
      return preState - data
    default:
      return preState
  }
}


function createStore(reducer, enhancer) {
  // 如果enhancer存在且是一个函数
  // 我们将createStore作为参数传给他
  // 这里应该返回一个新的createStore给我
  // 我在拿这个新的createStore执行得到一个store
  if (enhancer && typeof enhancer === 'function') {
    const newCreateStore = enhancer(createStore)
    const newStore = newCreateStore(reducer)
    return newStore
  }

  let state;
  let listeners = []; // 注册的回调

  function subscribe(callback) { // 保存回调
    listeners.push(callback)
  }

  function dispatch(action) { // 将回调依次执行
    state = reducer(state, action)

    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i]
      listener()
    }
  }

  function getState() {
    return state
  }
  const store = {
    createStore,
    subscribe,
    dispatch
  }
  return store
}

function combineReducers(reducerMap) {
  const reducerKeys = Object.keys(reducerMap) // 先把参数里所有的key拿出来

  // 返回值是一个普通结构的reducer函数
  const reducer = (state = {}, action) => {
    const newState = {};

    for (let i = 0; i < reducerKeys.length; i++) {
      // reducerMap里的每个key的值都是一个reduecer,我们把它拿出来运行下就可以得到对应key新的state值
      // 然后将所有的reducer返回的state按照参数里的key组装好
      // 最后再返回组装好的newState
      const key = reducerKeys[i];
      const currentReducer = reducerMap[key];
      const prevState = state[key]
      newState[key] = currentReducer(prevState, action)
    }
    return newState
  }
  return reducer;
}